package com.yunfinal.test;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;

/**
 * 总控制器
 * @author dufuzhong
 *
 */
public class IndexController extends Controller {
	
	public void index() {
		setAttr("name", decode(getCookie("websocket_name")));
		render("index.html");
	}
	
	/***
	 * 设置昵称
	 */
	public void getwebsocket(){
		String host = getPara("host");
		String name = getPara("name");
		String ids = getCookie("websocket_ids");
		
		if (StrKit.isBlank(ids)) {
			ids = StrKit.getRandomUUID();
			setCookie("websocket_ids", ids, (3 * 365 * 24 * 60 * 60), true);
		}
		
		name = WebSocketController.setNameByIds(ids, name);
		setCookie("websocket_name", encode(name), (3 * 365 * 24 * 60 * 60), true);
		
		renderJson(Ret.ok("url", "ws://" + host + "/websocket/" + ids));
	}

	private String encode(String name){
		if (StrKit.notBlank(name)) {
			try {
				return URLEncoder.encode(name, "utf-8");
			} catch (UnsupportedEncodingException e) {}
		}
		return null;
	}
	
	private String decode(String name){
		if (StrKit.notBlank(name)) {
			try {
				return URLDecoder.decode(name, "utf-8");
			} catch (UnsupportedEncodingException e) {}
		}
		return null;
	}
	
}
